package com.xue.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 
 * @author 北京八维博大科技 薛建新
 * @date 2022年4月28日 下午2:43:12
 * @Copyright 北京八维博大科技
 */
@EnableWebSecurity
public class SecurityConfig {
	@Bean
	SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
		// @formatter:off
		return http
		          //设置了<iframe>标签的“同源策略”，解决了上面出现的问题
				  //https://blog.csdn.net/weixin_43981241/article/details/108240756
		          .headers().frameOptions().sameOrigin()
		          .and()
		          //使得h2 console页面不去做csrf检查
		          .csrf()
		          .ignoringAntMatchers("/h2-console/**")
		          .and()
		          .authorizeRequests()
		          //使得访问h2 console时，不需要先登录系统
		          .antMatchers("/h2-console/**").permitAll()
		          .and()
		          
		          //需要拦截的API
		          .authorizeRequests()
		          .antMatchers(HttpMethod.POST, "/api/ingredients")
		          .hasAuthority("SCOPE_writeIngredients")
		          .antMatchers(HttpMethod.DELETE, "/api/ingredients")
		          .hasAuthority("SCOPE_deleteIngredients")
		          .and()
		          //开启 ResourceServer
		          .oauth2ResourceServer(oauth2 -> oauth2.jwt())
		          .build();
		// @formatter:on

	}

}
